// pages/my_comment/index.js
const app = getApp()
import api from '../../utils/api'
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
const chooseLocation = requirePlugin('chooseLocation')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    multiArray: [],
    multiIndex: [0, 0, 0],
    province: [],
    city: [],
    district: [],
    providx: 0,
    cityidx: 0,
    citys:[],

    imageBaseURL: app.imageBaseURL,
    picBaseURL:app.picBaseURL,
    step:1,
    blackmask:false,
    typelist:{
      guishupop:false,//组织归属
      quyupop:false,//所属区域
      sexpop:false,//性别
      occupationpop:false,//职业
      zzmmpop:false,//政治面貌
      zzlxpop:false,//组织类型
      zhucepop:false,//是否注册
      zhengdipop:false,//有无阵地
      addrpop:false,//地址
    },//分类列表，控制弹窗

    type:'',//接口返回的分类数据
    fileList: [],

    youthInput:false,//青年之家是否显示
    youthList:[],//搜索青年之家列表
    youthSearchPop:false,//搜索青年之家列表是否显示

    creditcodeInput:false,//信用代码是否显示
    addressInput:false,//阵地地址是否显示
    infoPop:false,//组织归属说明显示

    submitData:{
      id:'',//编辑时需要传，添加时不需要传
      youthid:'',//青年之家id
      youthtext:'',//青年之家
      guishu:'',//组织归属只接收2,3
      guishutext:'',
      'quyu[]':'',//区域id
      quyutext:'',
      org_name:'',//组织名称
      sqr_name:'',//申请人姓名 
      phone:'',//手机号
      age:'',//示例1男，2女
      sex:'',//示例1男，2女
      sextext:'',
      zzmm:'',//政治面貌
      zzmmtext:'',
      orgnum:'',//组织人数/规模
      orgtype:'',//组织类型
      orgtypetext:'',
      iszhuce:'',//是否注册，1注册，2未注册
      iszhucetext:'',
      creditcode:'',//信用代码
      zhendi:'',//是否有阵地，1有，2无
      zhenditext:'',
      address:'',//阵地地址
      note:'',//简介
      'urlid[]':'',//图片地址
      location:{}
    },
  },
  //显示组织归属说明
  showInfoPop(){
    this.setData({
      infoPop:true
    })
  },
  hideInfoPop(){
    this.setData({
      infoPop:false
    })
  },
  //下一步
  next(){
    if(this.data.submitData.guishu == '' || this.data.submitData.guishutext == ''){Toast('请选择组织归属'); return}
    if(this.data.youthInput && this.data.submitData.youthid == ''){Toast('请搜索青年之家'); return} 
    if(this.data.submitData['quyu[]'] == '' || this.data.submitData.quyutext == '' || this.data.submitData.quyutext == null){Toast('请选择所属区域'); return} 
    if(this.data.submitData.org_name == ''){Toast('请输入组织名称'); return} 
    if(this.data.submitData.sqr_name == ''){Toast('请输入申请人姓名'); return} 
    if(this.data.submitData.phone == ''){Toast('请输入手机号'); return} 
    if(this.data.submitData.age == ''){Toast('请输入年龄'); return} 
    if(this.data.submitData.sex == ''){Toast('请选择性别'); return} 
    if(this.data.submitData.zzmm == '' && (this.data.submitData.zzmmtext == '' || this.data.submitData.zzmmtext == null)){Toast('请选择政治面貌'); return} 
    if(this.data.submitData.orgnum == ''){Toast('请输入组织现有人数'); return}  
    if(this.data.submitData.orgtype == '' && (this.data.submitData.orgtypetext == '' || this.data.submitData.zzmmtext == null)){Toast('请选择组织类型'); return} 
    if(this.data.submitData.iszhuce == ''){Toast('请选择是否注册'); return} 
    if(this.data.creditcodeInput && this.data.submitData.creditcode == ''){Toast('请输入信用代码'); return} 
    if(this.data.submitData.zhendi == ''){Toast('请选择是否有阵地'); return} 
    if(this.data.addressInput && this.data.submitData.address == ''){Toast('请输入阵地地址'); return} 
    if(this.data.submitData.note == ''){Toast('请输入组织简介'); return} 
    wx.navigateTo({
      url: '/pages/my_team_upload/index?all=' + JSON.stringify(this.data.submitData),
    })
  },
  //显示下拉框
  showMask(e){
    let typepop = e.currentTarget.dataset.type
    this.data.typelist[typepop] = true;
    this.setData({
      typelist:this.data.typelist,
      blackmask:true
    })
  },
  //关闭下拉框
  hidePop(e){
    let typelist = {
      guishupop:false,//组织归属
      quyupop:false,//所属区域
      sexpop:false,//性别
      occupationpop:false,//职业
      zzmmpop:false,//政治面貌
      zzlxpop:false,//组织类型
      zhucepop:false,//是否注册
      zhengdipop:false,//有无阵地
      addrpop:false,//地址
    }
    this.setData({
      typelist:typelist,
      blackmask:false
    })
  },
  //选择内容赋值
  selected(e){
    let textkey = e.currentTarget.dataset.type
    let text = e.currentTarget.dataset.text
    let valkey = e.currentTarget.dataset.typeval
    let val = e.currentTarget.dataset.val
    this.data.submitData[textkey] = text
    this.data.submitData[valkey] = val
    this.setData({
      submitData:this.data.submitData
    })

    switch(textkey){
      case "guishutext":
        //组织归属选择 -入驻==》显示青年之家输入框
        if(val == 2){
          this.setData({
            youthInput:true
          })
        }else{
          this.setData({
            youthInput:false
          })
        }
        break;
      case "youthtext":
        //所属区域
        this.setData({
          youthSearchPop:false
        })
        break;
      case "iszhucetext":
        //是否注册
        if(val == 1){
          this.setData({
            creditcodeInput:true
          })
        }else{
          this.setData({
            creditcodeInput:false
          })
        }
  
        break;
      case "zhenditext":
          //有无阵地
          if(val == 1){
            this.setData({
              addressInput:true
            })
          }else{
            this.setData({
              addressInput:false
            })
          }
  
          break;
      default:
        break
    }
    this.hidePop()
  },
  //输入内容赋值
  selectedInput(e){
    let valkey = e.currentTarget.dataset.typeval
    this.data.submitData[valkey] = e.detail
    this.setData({
      submitData:this.data.submitData
    })
  },
  showQuyuPop(){
    // this.setData({
    //   youthSearchPop:false
    // })
  },
  //回显青年之家
  async getInfo(){
    let data={}
    data['flag'] = 'social_organization_query'
    
    const {recode, result, message} = await api.send(data)
    if(recode === 'SUCC') {
      let data = result;
      this.data.typelist.quyupop = data.guishu == 2 ?  true : false;
      let creditcodeInput = data.iszhuce == 1 ?  true : false;
      let addressInput = data.zhendi == 1 ?  true : false;
      
      let submit = {
        id:data.id,//编辑时需要传，添加时不需要传
        youthid:data.youthid,//青年之家id
        youthtext:data.youthname,//青年之家
        guishu:data.guishu,//组织归属只接收2,3
        guishutext:data.guishu == 2 ? '入驻青年之家的社会组织' :'其他联系服务的青年组织',
        'quyu[]':data.quyu,//区域id
        quyutext:data.quyutext,
        org_name:data.org_name,//组织名称
        sqr_name:data.sqr_name,//申请人姓名 
        phone:data.phone ? data.phone : '',//手机号
        age:data.age,//示例1男，2女
        sex:data.sex,//示例1男，2女
        sextext:data.sex == 1 ? '男' : '女',
        zzmm:data.zzmm,//政治面貌
        zzmmtext:data.zzmmtext ? data.zzmmtext :'',
        orgnum:data.orgnum,//组织人数/规模
        orgtype:data.orgtype,//组织类型
        orgtypetext:data.orgtypetext ? data.orgtypetext :'',
        iszhuce:data.iszhuce,//是否注册，1注册，2未注册
        iszhucetext:data.iszhuce == 1 ? '注册' : '未注册',
        creditcode:data.creditcode,//信用代码
        zhendi:data.zhendi,//是否有阵地，1有，2无
        zhenditext:data.zhendi == 1 ? '有' : '无',
        address:data.location.address,//阵地地址
        note:data.note,//简介
        'urlid[]':data.urlimg,//图片地址
        location:data.location,
        'location[lat]':data.lat,
        'location[lng]':data.lng,
      }
      this.setData({
        submitData:submit,
        creditcodeInput,addressInput,
        typelist:this.data.typelist
      })
      
      
    }else {
      // Toast(message)
    }
  },
  //搜索青年之家
  async selectedYouth(e){
    let data={}
    data['flag'] = 'social_youth_query'
    data['searchval'] = e.detail
    const {recode, result, message} = await api.send(data)
    if(recode === 'SUCC') {
      this.setData({
        youthList:result,
        youthSearchPop:true
      })
      
    }else {
      Toast(message)
    }
  },

  //申请组织-获取分类
  async getType () {
    let data={}
    data['flag'] = 'social_organization_data'
    const {recode, result, message} = await api.send(data)
    if(recode === 'SUCC') { 
      let citys = result.addr
      let p = [],
      c = [],
      d = [];
      for (var i = 0; i < citys.length; i++) {
        p.push(citys[i].label);
      }
      if (citys[0].children) {
        for (var i = 0; i < citys[0].children.length; i++) {
          c.push(citys[0].children[i].label);
        }
      }

      if (citys[0].children && citys[0].children[0].children) {
        for (var i = 0; i < citys[0].children[0].children.length; i++) {
          d.push(citys[0].children[0].children[i].label);
        }
      }
  
      this.setData({
        multiArray: [p, c, d],
        province: p,
        city: c,
        district: d,
        type:result,
        citys
      })
      
    }else {
      Toast(message)
    }
  },

  // 城市选择
  bindMultiPickerChange: function (e) {
    
    console.log('picker发送选择改变，携带值为', e.detail.value)
    let citys = this.data.citys;
    // if( citys[0].label=='全国' ) citys.splice(0,1);
    let idx = e.detail.value;
    let curr = citys[idx[0]].children[idx[1] ];
    if (curr && curr.children && curr.children.length > 0 && curr.children[0].label != '')
      curr = curr.children[idx[2] ];

    let currobj = {};

      // 选择到县级
      currobj['label'] = citys[idx[0]].children[idx[1] ].children[idx[2]].label;
      currobj['value'] = citys[idx[0]].children[idx[1] ].children[idx[2] ].value;
    
    let locid = [];
    locid[0] = currobj.value
    this.data.submitData["quyu[]"] = currobj.value
    this.data.submitData.quyutext = citys[idx[0]].label + '-' + citys[idx[0]].children[idx[1] ].label + '-' + currobj['label']
    this.setData({
      multiIndex: e.detail.value,
      currcity: currobj.label,
      currcitycode: currobj.value,
      locid,
      submitData:this.data.submitData
    })
  },
  bindMultiPickerColumnChange: function (e) {
    console.log(e);
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    let citys = this.data.citys;
    // if( citys[0].label=='全国' ) citys.splice(0,1);

    let p = this.data.province;
    if (e.detail.column == 0) { //第1列
      this.data.providx = e.detail.value;
      let city = citys[e.detail.value];
      let c = [],  d = [];
      if (e.detail.column == 0 && e.detail.value == 0) {
        c = [];
        d = [];
      }
      for (let i = 0; i < city.children.length; i++) {
        c.push(city.children[i].label);

      }
      if (e.detail.column >= 0) {
        if (city.children[0].children) {
          for (let i = 0; i < city.children[0].children.length; i++) {
            d.push(city.children[0].children[i].label);
          }
        }
      }
      
      this.setData({
        multiArray: [p, c, d],
        multiIndex: [this.data.providx, 0, 0],
        city: c,
        district: d,
        providx: this.data.providx
      })
    };
    if (e.detail.column == 1) { //第1列

      this.data.cityidx = e.detail.value;
      let city = citys[this.data.providx].children[e.detail.value ];
      console.log(city)
      let d = [];
      if (e.detail.value >= 0) {
        if (city && city.children) {
          for (let i = 0; i < city.children.length; i++) {
            d.push(city.children[i].label);

          }
        }
      }

      this.setData({
        multiArray: [this.data.province, this.data.city, d],
        multiIndex: [this.data.providx, this.data.cityidx, 0],
        district: d,
        cityidx: this.data.cityidx
      })
    };

  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getInfo()
    this.getType()
    this.data.submitData.location={}
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const location = chooseLocation.getLocation()
    console.log(location)
    if(location){
      let loc = {}
      loc['lat'] = location.latitude
      loc['lng'] = location.longitude
      loc['address'] = location.address
      let str = 'submitData.location'
      this.data.submitData['location[lat]'] = location.latitude
      this.data.submitData['location[lng]'] = location.longitude
      this.setData({[str]:loc,['submitData.address']:loc.address,submitData:this.data.submitData})
    }
  },
  
  clickaddr(){
    const key = '5CDBZ-LIMKU-OHTV4-BKE65-4PI7H-KDFWH'; //使用在腾讯位置服务申请的key
    const referer = 'youthapp'; //调用插件的app的名称
    const location = '';
    const category = '';
    
    wx.navigateTo({
      url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&location=${location}&category=${category}`
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})